import time
import sched
import threading

import etcd3

client = etcd3.client(host="127.0.0.1", port=2379)  # etcd默认的启动配置

# etcd key的过期时间,又叫租期续约时间
lease_timeout = 10
lease = client.lease(lease_timeout)
is_lease = False

# 定时任务对象
schedule = sched.scheduler(time.time, time.sleep)


def something_schedule():
    t = threading.Thread(target=schedul_job)
    t.setDaemon(True)
    t.start()


def schedul_job():
    inc = 6  # 定时任务,循环时间
    schedule.enter(0, 0, lease_server, (inc, schedule))  # 加入定时任务
    schedule.run()  # 执行


def lease_server(inc, schedule):
    global is_lease
    # 进行租期约需
    path = "account.http"
    value = "127.0.0.1:5002"
    key = "{}/{}".format(path, lease.id)
    if is_lease:
        print("------------continue---------", time.time())
        lease.refresh()  # 刷新续约时间, 如果直接put,会触发监听变化,续约则不会。
    else:
        client.put(key, value, lease=lease)
        is_lease = True
        print("-----------regist---------", time.time())
    # 此处让定时任务循环执行,类似一个递归的样子
    schedule.enter(inc, 0, lease_server, (inc, schedule))
